package com.mhs.rssfeed;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.mhs.mhs_gui.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class NewsDetails extends Activity{
	SingleNewsItem selectedNewsItem;
	ArrayList<SingleNewsItem> newsList = new ArrayList<SingleNewsItem>();
	
	ArrayAdapter<String> aa;
	
	ListView myListView;
	String urlAddress = "";
	String urlCaption = "";
	
	Context context = getApplication();
	final boolean DEBUG_MODE = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rssfeeder_details);
        myListView = (ListView)this.findViewById(R.id.lv_rssfeeder_details);
        
        Intent myLocalIntent = getIntent();
        
        Bundle myBundle = myLocalIntent.getExtras();    
        urlAddress = myBundle.getString("urlAddress");
        urlCaption = myBundle.getString("urlCaption");
           
        this.setTitle("Tin tức sức khỏe - " + urlCaption + " \t");
        
        myListView = (ListView)this.findViewById(R.id.lv_rssfeeder_details);
        myListView.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> _av, View _v, int _index, long _id) {
            	selectedNewsItem = newsList.get(_index);
            	Uri myLink =  Uri.parse(selectedNewsItem.getLink());
            	Intent webIntent = new Intent(Intent.ACTION_VIEW, myLink);
            	startActivity(webIntent);
            }
       });  
        
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		try {
			//explain the use of LogCat and printStackTrace (Log better!)
			if (DEBUG_MODE) Log.i("***connecting*** ", urlAddress.toString());
			
			// setting / opening the connection using urlAddress which is
			// a value such as: http://www.npr.org/rss/rss.php?id=1001
			URL url = new URL(urlAddress);			
			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream in = httpConnection.getInputStream();
				// define a document builder to act on incoming stream
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				// make XML parse tree for incoming stream
				Document dom = db.parse(in);
				// define access nodes in the parse tree
				Element docEle = dom.getDocumentElement();

				// look for individual news ("items" in this case)
				// put items in a NodeList collection (nl)
				NodeList nl = docEle.getElementsByTagName("item");
				if ((nl != null) && (nl.getLength() > 0)) {
					for (int i = 0; i < nl.getLength(); i++) {
						dissectNode(nl, i);
					}
				}
			}			
			int layoutID = R.layout.my_simple_list_item_1;
			ArrayAdapter<SingleNewsItem> aaNews = new ArrayAdapter<SingleNewsItem>(this, layoutID, newsList);
			myListView.setAdapter(aaNews);			

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(context, "Trouble!!!", 1).show();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	
	public void dissectNode(NodeList nl, int i){
    	try {
			Element entry =  (Element) nl.item(i);
			Element title = (Element) entry.getElementsByTagName("title").item(0);
			Element description = (Element) entry.getElementsByTagName("description").item(0);
			Element pubDate = (Element) entry.getElementsByTagName("pubDate").item(0);
			Element link = (Element) entry.getElementsByTagName("link").item(0);

			String titleValue = title.getFirstChild().getNodeValue();
			String descriptionValue =description.getFirstChild().getNodeValue();
			String dateValue = pubDate.getFirstChild().getNodeValue();
			String linkValue = link.getFirstChild().getNodeValue();
			
			SingleNewsItem singleItem = new SingleNewsItem(dateValue, titleValue, descriptionValue, linkValue);
			newsList.add(singleItem);
		} catch (DOMException e) {
			e.printStackTrace();
		}    
    }
}
